package com.dingreading.cloud.admin.controller;

import com.dingreading.cloud.admin.dto.vo.TicketUserVO;
import com.dingreading.cloud.admin.entity.NjTicketOrder;
import com.dingreading.cloud.admin.entity.NjTicketUser;
import com.dingreading.cloud.admin.entity.NjTicketUserLog;
import com.dingreading.cloud.admin.service.NjTicketOrderService;
import com.dingreading.cloud.admin.service.NjTicketUserLogService;
import com.dingreading.cloud.admin.service.NjTicketUserService;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.*;
import com.dingreading.cloud.common.util.excel.ExcelHandler;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/ticketUser")
@Api(tags = "管理端-南京门票用户管理")
public class NjTicketUserController {

    @Resource
    private NjTicketUserService ticketUserService;
    @Resource
    private NjTicketUserLogService ticketUserLogService;
    @Resource
    private NjTicketOrderService ticketOrderService;

    @ApiOperation(value = "门票用户分页列表")
    @PostMapping(value = "/pageList")
    public R<Object> pageList(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "机构名称/姓名/手机号") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "门票类型 1.参会票 2.观展票") @RequestParam(value = "ticketType", required = false) Integer ticketType,
            @ApiParam(value = "领票状态 0.未领票 1.已领票") @RequestParam(value = "getStatus", required = false) Integer getStatus,
            @ApiParam(value = "参会证领取状态 0.未领取 1.已领取") @RequestParam(value = "permitStatus", required = false) Integer permitStatus
    ) {
        Page<NjTicketUser> page = this.ticketUserService.pageList(pageUtil, keyword, ticketType, permitStatus, getStatus);

        PageBeanDto dto = new PageBeanDto();
        dto.setList(page.getRecords());
        dto.setTotal(page.getTotalRow());
        return R.ok(dto);
    }

//    @ApiOperation(value = "展商用户分页列表")
//    @PostMapping(value = "/exhibitorPageList")
//    public R<Object> exhibitorPageList(
//            @ApiParam(value = "分页公共类") PageUtil pageUtil,
//            @ApiParam(value = "机构名称/姓名/手机号") @RequestParam(value = "keyword", required = false) String keyword
//    ) {
//        
//
//        Page<NjExhibitor> page = this.exhibitorService.pageList(pageUtil, keyword);
//
//        PageBeanDto dto = new PageBeanDto();
//        dto.setList(page.getRecords());
//        dto.setTotal(page.getTotalRow());
//        return R.ok(dto);
//    }

//    @ApiOperation(value = "展位预订用户分页列表")
//    @PostMapping(value = "/bookUserPageList")
//    public R<Object> bookUserPageList(
//            @ApiParam(value = "分页公共类") PageUtil pageUtil,
//            @ApiParam(value = "机构名称/姓名/手机号") @RequestParam(value = "keyword", required = false) String keyword
//    ) {
//        
//
//        Page<NjBookUser> page = this.bookUserService.pageList(pageUtil, keyword);
//
//        PageBeanDto dto = new PageBeanDto();
//        dto.setList(page.getRecords());
//        dto.setTotal(page.getTotalRow());
//        return R.ok(dto);
//    }

    @ApiOperation(value = "付款记录")
    @PostMapping(value = "/payRecordPageList")
    public R<Object> payRecordPageList(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "机构名称/姓名/手机号") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "支付状态 0.待支付 1.已支付") @RequestParam(value = "payStatus", required = false) Integer payStatus
    ) {
        Page<NjTicketOrder> page = this.ticketOrderService.pageList(pageUtil, keyword, payStatus);

        PageBeanDto dto = new PageBeanDto();
        dto.setList(page.getRecords());
        dto.setTotal(page.getTotalRow());
        return R.ok(dto);
    }

    @ApiOperation(value = "App扫码记录分页列表")
    @PostMapping(value = "/userLogPageList")
    public R<Object> userLogPageList(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "机构名称/姓名/手机号/类型") @RequestParam(value = "keyword", required = false) String keyword
    ) {
        Page<NjTicketUserLog> page = this.ticketUserLogService.pageList(pageUtil, keyword);

        PageBeanDto dto = new PageBeanDto();
        dto.setList(page.getRecords());
        dto.setTotal(page.getTotalRow());
        return R.ok(dto);
    }

    @ApiOperation(value = "编辑门票用户信息")
    @PostMapping(value = "/newBean")
    public R<Object> newBean(
            @ApiParam(value = "用户uid") @RequestParam(value = "uid") String uid,
            @ApiParam(value = "手机号") @RequestParam(value = "phone", required = false) String phone,
            @ApiParam(value = "用户姓名") @RequestParam(value = "name", required = false) String name,
            @ApiParam(value = "机构名称") @RequestParam(value = "corpName", required = false) String corpName,
            @ApiParam(value = "门票类型 1.参会票 2.观展票") @RequestParam(value = "ticketType", required = false) Integer ticketType,
            @ApiParam(value = "用户类型") @RequestParam(value = "userType", required = false) String userType,
            @ApiParam(value = "参会证个数") @RequestParam(value = "permitNum", required = false) Integer permitNum,
            @ApiParam(value = "来源") @RequestParam(value = "source", required = false) String source
    ) {
        NjTicketUser data = ticketUserService.getByUid(uid);
        if (null == data) return R.fail("门票用户获取失败");

        data.setPhone(phone);
        data.setName(name);
        data.setCorpName(corpName);
        data.setTicketType(ticketType);
        if (ticketType.equals(1)) {
            data.setTicketTypeName("参会票");
            data.setPermitNum(permitNum);
        } else {
            data.setTicketTypeName("观展票");
            data.setPermitNum(0);
        }
        data.setUserType(userType);
        data.setSource(source);
        ticketUserService.saveOrUpdate(data);
        return R.ok();
    }

    @ApiOperation(value = "导入参会/观展票用户")
    @PostMapping(value = "/importTicketUser")
    public R<Object> importTicketUser(
            @ApiParam(value = "参会票用户数据excel") @RequestPart(value = "file") MultipartFile multipartFile,
            @ApiParam(value = "门票类型 1.参会票 2.观展票") @RequestParam(value = "ticketType") Integer ticketType
    ) throws Exception {
        List<TicketUserVO> voList = ExcelHandler.importExcel(multipartFile, TicketUserVO.class, null);
        if (CollectionUtils.isEmpty(voList)) return R.fail("导入的数据为空");

        Date time = DateUtil.getNowDatetime();
        List<NjTicketUser> newList = new ArrayList<>();
        Set<String> phoneList = new HashSet<>();
        for (int i = 0; i < voList.size(); i++) {
            TicketUserVO userVO = voList.get(i);
            String name = userVO.getName();
            String phone = userVO.getPhone();
            String corpName = userVO.getCorpName();
            String userType = userVO.getUserType();
            String source = userVO.getSource();
            Integer permitNum = userVO.getPermitNum();
            if (StringUtils.isBlank(name)) return R.fail("用户姓名错误, 行号：" + (i + 1));
            if (StringUtils.isBlank(phone)) return R.fail("手机号错误, 行号：" + (i + 1));
            phone = StringUtils.deleteWhitespace(phone);
            if (phone.length() != 11) return R.fail("手机号错误, 行号：" + (i + 1));

            phoneList.add(phone);

            NjTicketUser user = new NjTicketUser();
            user.setName(name);
            user.setPhone(phone);
            user.setCorpName(corpName);
            // 用户类型 观展人员 工作人员 媒体 展商 嘉宾
            user.setUserType(userType);
            user.setSource(source);
            if (ticketType.equals(1))
                user.setPermitNum(NepUtil.nullToZero(permitNum));
            else
                user.setPermitNum(0);
            newList.add(user);
        }

        if (CollectionUtils.isEmpty(newList))
            return R.fail("转换的数据为空");

        if (phoneList.size() != voList.size())
            return R.fail("手机号码重复了");

        ArrayList<String> phones = new ArrayList<>(phoneList);
        List<NjTicketUser> exList = ticketUserService.getByPhones(phones);
        if (CollectionUtils.isNotEmpty(exList)) {
            String exPhone = exList.stream().map(NjTicketUser::getPhone).collect(Collectors.joining(","));
            throw new DescribeException("手机号已被注册手机号：" + exPhone);
        }

//        Map<String, NjExhibitor> exhibitorMap = new HashMap<>();
//        List<NjExhibitor> exhibitorList = exhibitorService.getByPhones(phones);
//        if (CollectionUtils.isNotEmpty(exhibitorList)) {
//            exhibitorMap = exhibitorList.stream().collect(Collectors.toMap(NjExhibitor::getPhone, Function.identity()));
//        }

        for (NjTicketUser user : newList) {
            user.setYear("2023");
            user.setUid(KitUtil.getUuid() + KitUtil.getRandomStr(4));

            String ticketTypeName = "参会票";
            String userType = user.getUserType();
            int payStatus = 0;
            String payStatusName = "未付款";
            /*NjExhibitor exhibitor = exhibitorMap.get(user.getPhone());
            if (exhibitor != null) {
                ticketType = 1;
                ticketTypeName = "参会票";
                userType = "展商";
                payStatus = 1;
                payStatusName = "已付款";
            } else */
            if (ticketType.equals(1)) {
                ticketType = 1;
                ticketTypeName = "参会票";
                payStatus = 1;
                payStatusName = "已付款";
            } else if (ticketType.equals(2)) {
                ticketType = 2;
                ticketTypeName = "观展票";
            }

            user.setTicketType(ticketType);
            user.setTicketTypeName(ticketTypeName);
            user.setUserType(userType);
            user.setGetStatus(0);
            user.setGetStatusName("未领票");
            user.setPermitStatus(0);
            user.setPermitStatusName("未领取");
            user.setPaymentStatus(payStatus);
            user.setPaymentStatusName(payStatusName);
            user.setAddTime(time);
        }
        ticketUserService.saveOrUpdateBatch(newList);

        return R.ok();
    }

//    @ApiOperation(value = "导入参展票用户（展商）")
//    @PostMapping(value = "/importExhibitor")
//    public R<Object> importExhibitor(
//            @ApiParam(value = "参展票用户数据excel") @RequestPart(value = "file") MultipartFile multipartFile
//    ) throws Exception {
//        
//
//        List<TicketUserVO> voList = excelHandler.importExcel(multipartFile, TicketUserVO.class, null);
//        if (CollectionUtils.isEmpty(voList)) return R.fail("导入的数据为空");
//
//        Date time = DateUtil.getNowDatetime();
//        List<NjExhibitor> newList = new ArrayList<>();
//        Set<String> phoneList = new HashSet<>();
//        for (int i = 0; i < voList.size(); i++) {
//            TicketUserVO userVO = voList.get(i);
//            String name = userVO.getName();
//            String phone = userVO.getPhone();
//            String corpName = userVO.getCorpName();
//            String userType = userVO.getUserType();
//            String source = userVO.getSource();
//            Integer permitNum = userVO.getPermitNum();
//            if (StringUtils.isBlank(name)) return R.fail("用户姓名错误, 行号：" + (i + 1));
//            if (StringUtils.isBlank(phone)) return R.fail("手机号错误, 行号：" + (i + 1));
//            phone = StringUtils.deleteWhitespace(phone);
//            if (phone.length() != 11) return R.fail("手机号错误, 行号：" + (i + 1));
//
//            phoneList.add(phone);
//
//            NjExhibitor user = new NjExhibitor();
//            user.setName(name);
//            user.setPhone(phone);
//            user.setCorpName(corpName);
//            user.setSource(source);
//            newList.add(user);
//        }
//
//        if (CollectionUtils.isEmpty(newList))
//            return R.fail("转换的数据为空");
//
//        if (phoneList.size() != voList.size())
//            return R.fail("手机号码重复了");
//
//        ArrayList<String> phones = new ArrayList<>(phoneList);
//        List<NjExhibitor> exList = exhibitorService.getByPhones(phones);
//        if (CollectionUtils.isNotEmpty(exList)) {
//            String exPhone = exList.stream().map(NjExhibitor::getPhone).collect(Collectors.joining(","));
//            throw new DescribeException("手机号已被注册手机号：" + exPhone);
//        }
//
//        for (NjExhibitor user : newList) {
//            user.setYear("2023");
//            user.setAddTime(time);
//        }
//        exhibitorService.saveOrUpdateBatch(newList);
//
//        // 已有观展门票的用户改为参会门票和展商
//        ticketUserService.updateTicketTypAndUserType(phones);
//
//        return R.ok();
//    }

}